﻿using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Mvc;
using Microsoft.VisualBasic;

using SRM.Application.PageResult.IServices;

using SRM.Core.Extension;
using SRM.Core.Models;
using SRM.Core.Models.Base;
using SRM.Core.Repositories;

using System;
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using SRM.Core.Utility;

namespace SRM.WebSite.Controllers
{
    public class PurchaseOrderController : Controller
    {
        private readonly IRepository<PurchaseOrder> _purchaseOrderRepository;
        private readonly IRepository<PurchaseOrderDetail> _purchaseOrderDtlRepository;
        private readonly IPurchaseOrderServer _purchaseOrderServer;
        private readonly IPurchaseOrderDtlServer _purchaseOrderDtl;
        private readonly ILogger<PurchaseOrderController> _logger;
        private readonly DataProtector _dataProtector;

        public PurchaseOrderController(
            IRepository<PurchaseOrder> purchaseOrderRepository,
            IRepository<PurchaseOrderDetail> purchaseOrderDtlRepository,
            IPurchaseOrderDtlServer purchaseOrderDtl,
            IPurchaseOrderServer purchaseOrderServer
            , ILogger<PurchaseOrderController> logger,
            DataProtector dataProtector)
        {
            _purchaseOrderRepository = purchaseOrderRepository;
            _purchaseOrderDtlRepository = purchaseOrderDtlRepository;
            _purchaseOrderDtl = purchaseOrderDtl;
            _purchaseOrderServer = purchaseOrderServer;
            _logger = logger;
            _dataProtector = dataProtector;
        }


        public async Task<IActionResult> Index(PagerModelInput input)
        {
            var list = await _purchaseOrderServer.GetPurchaseOrderList(input);
            list.Data = list.Data.Select(p =>
            {
                p.EncryptedId = _dataProtector.DataEncryption(p.Id);
                return p;
            }).ToList();
            return View(list);
        }

        [HttpPost]
        public async Task<IActionResult> PurchaseOrderReview()
        {
            _logger.LogInformation("采购单审核...");
            if (ModelState.IsValid)
            {
                var action = Request.Form["action"].ToString();
                var Ids = Request.Form["Ids"].ToString();
                List<int> IdList = CompilerExt.ConverToList(Ids);
                var purchaseOrderList =
                    await _purchaseOrderRepository.GetAllListAsync(p => IdList.Contains(p.Id));
                if (purchaseOrderList == null || purchaseOrderList.Count == 0)
                {
                    return Json($"no:采购ID的信息不存在，请刷新重试");
                }
                var executeAction = (ExecuteActionEnum)Enum.Parse(typeof(ExecuteActionEnum), action);
                PurchaseOrderStateEnum? @enum = null;
                string error = "";
                string userName = LoginUser.LoginUsers.UserName;
                DateTime? dateTime = DateTime.Now;
                switch (executeAction)
                {
                    case ExecuteActionEnum.审核:
                        purchaseOrderList.ForEach(s =>
                        {
                            if (s.ReviewState != PurchaseOrderStateEnum.未审核)
                            {
                                error = $"选择的采购单数据状态存在不为 {PurchaseOrderStateEnum.未审核}的订单，操作失败！";
                                return;
                            }
                            @enum = PurchaseOrderStateEnum.已审核;
                        });
                        break;
                    case ExecuteActionEnum.撤销审核:
                        purchaseOrderList.ForEach(s =>
                        {
                            if (s.ReviewState != PurchaseOrderStateEnum.已审核)
                            {
                                error = $"选择的采购单数据状态存在不为 {PurchaseOrderStateEnum.已审核}的订单，操作失败！";
                                return;
                            }
                            @enum = PurchaseOrderStateEnum.未审核;
                            userName = "";
                            dateTime = null;
                        });
                        break;
                    case ExecuteActionEnum.仓库回复:
                        purchaseOrderList.ForEach(s =>
                        {
                            if (s.ReviewState != PurchaseOrderStateEnum.已审核)
                            {
                                error = $"选择的采购单数据状态存在不为 {PurchaseOrderStateEnum.已审核}的订单，操作失败！";
                                return;
                            }
                            @enum = PurchaseOrderStateEnum.仓库确认;
                        });
                        break;
                    case ExecuteActionEnum.仓库驳回:
                        purchaseOrderList.ForEach(s =>
                        {
                            if (s.ReviewState != PurchaseOrderStateEnum.仓库确认)
                            {
                                error = $"选择的采购单数据状态存在不为 {PurchaseOrderStateEnum.仓库确认}的订单，操作失败！";
                                return;
                            }
                            @enum = PurchaseOrderStateEnum.已审核;
                        });
                        break;

                    case ExecuteActionEnum.接收订单:
                        purchaseOrderList.ForEach(s =>
                        {
                            if (s.ReviewState != PurchaseOrderStateEnum.仓库确认)
                            {
                                error = $"选择的采购单数据状态存在不为 {PurchaseOrderStateEnum.仓库确认}的订单，操作失败！";
                                return;
                            }
                            @enum = PurchaseOrderStateEnum.已接单;
                        });
                        break;
                    case ExecuteActionEnum.撤销接单:
                        purchaseOrderList.ForEach(s =>
                        {
                            if (s.ReviewState != PurchaseOrderStateEnum.已接单)
                            {
                                error = $"选择的采购单数据状态存在不为 {PurchaseOrderStateEnum.已接单}的订单，操作失败！";
                                return;
                            }
                            @enum = PurchaseOrderStateEnum.仓库确认;
                        });
                        break;
                    case ExecuteActionEnum.关闭:
                        @enum = PurchaseOrderStateEnum.关闭;
                        break;
                }
                if (string.IsNullOrEmpty(error) && @enum.HasValue)
                {
                    for (int i = 0; i < purchaseOrderList.Count; i++)
                    {
                        purchaseOrderList[i].ReviewState = @enum.Value;
                        purchaseOrderList[i].ReviewBy = userName;
                        purchaseOrderList[i].ReviewDate = dateTime;
                        purchaseOrderList[i].ReviewStateString = @enum.Value.ToString();
                        await _purchaseOrderRepository.UpdateAsync(purchaseOrderList[i]);
                    }
                    return Json("ok:操作成功");
                }
                else
                {
                    return Json($"no:{error}");
                }
            }
            return View();
        }

        //明细
        public async Task<IActionResult> PreviewPurchase(string EncryptedId)
        {
            int Id = _dataProtector.DataDecryptionSign(EncryptedId);
            var list = await _purchaseOrderDtlRepository.GetAllListAsync(p => p.PurchaseOrderId == Id);
            return View(list);
        }

        public async Task<IActionResult> PurchaseOrderDtl(PagerModelInput input)
        {
            var list = await _purchaseOrderDtl.GetPurchaseOrderDtl(input);
            return View(list);
        }

        public async Task<IActionResult> PurchaseOrderInfo(PagerModelInput input)
        {
            var list = await _purchaseOrderServer.GetPurchaseOrderList(input);
            return View(list);
        }

        [HttpPost]
        public async Task<JsonResult> GetPurchaseOrderById()
        {
            int.TryParse(Request.Form["purchaseOrderId"], out int purchaseOrderId);
            var purchaseOrder =
                await _purchaseOrderRepository.FirstOrDefaultAsync(p => p.Id == purchaseOrderId);

            purchaseOrder.PurchaseOrderTypeString = Enum.GetName(typeof(PurchaseOrderTypeEnum), Convert.ToInt32(purchaseOrder.PurchaseOrderType)).ToString();

            purchaseOrder.ReviewStateString = Enum.GetName(typeof(PurchaseOrderStateEnum), Convert.ToInt32(purchaseOrder.ReviewState)).ToString();

            if (purchaseOrder != null)
                return Json(purchaseOrder);
            else
                return Json(false);
        }
    }
}
